<?php
/**
 * 
 * @author Radovan Dvorsky
 * @version 20091227
 */
class My_Csv_Import {
	
	const ALLOWED_FILE_TYPE = 'text/comma-separated-values'; 
	
	/**
	 * Obsahuje vsetky importovane data
	 * @var array
	 */
	protected $_data = array();
	
	/**
	 * @var array
	 */	
	protected $_assocData = array();
	
	/**
	 * Meno importovaneho suboru
	 * @var string
	 */
	protected $_file;
	
	/**
	 * Obsahuje format pre ulozenie hodnot do pola
	 * @var My_Pattern
	 */
	protected $_pattern;
	
	/**
	 * Csv options (default values) 
	 * @var array
	 */
	protected $_options = array(
			'delimiter' => ',',
			'enclosure' => '"'
	);
	
	/**
	 * 
	 * @param string $filename
	 * @param My_Pattern $pattern
	 */
	function __construct($file = null,My_Pattern $pattern = null) {
		
		if($pattern != null){
			$this->setPattern($pattern);
		}		
		
		if($file != null){
			$this->setFile($file);
		}
		
	}
		
	/**
	 * Getter _pattern
	 */
	public function getPattern(){
		return $this->_pattern;
	}
	
	/**
	 * Getter _file
	 */
	public function getFile(){
		return $this->_file;
	}
	
	/**
	 * Setter _pattern
	 * @param My_Pattern $pattern
	 */
	public function setPattern(My_Pattern $pattern){
		
		if(!$pattern instanceof My_Pattern){
			throw new My_Csv_Exception($pattern . ' is not instance of My_Pattern'); 
		}

		$this->_pattern = $pattern;
	}
	
	/**
	 * Setter _file
	 * @param string $filename
	 */
	public function setFile($file){		
		
		if(!$this->isRightFileType($file)){			
			require_once 'library/My/Csv/Exception.php';
			throw new My_Csv_Exception('Bad filetype');			
		}		
		
		if(!@$handle = fopen($file['tmp_name'],'r')){
			require_once 'library/My/Csv/Exception.php';			
			throw new My_Csv_Exception('Cannot open csv file ' . $file['tmp_name']);			
		}
		
		$this->_file = $file;
		
		
		while(($data = fgetcsv($handle,100,$this->_options['delimiter'],$this->_options['enclosure'])) !== false ){
			$this->_data[] = $data;	
		}	
		
		fclose($handle);		
		
		return true;		
	}
	
	/**
	 * Nastavenie vlastnosti csv importu
	 * @param string $delimiter
	 * @param string $enclosure
	 */
	public function setCsvOptions($delimiter = ",", $enclosure = '"'){
		
		$this->_options = array(
			'delimiter' => $delimiter,
			'enclosure' => $enclosure
		);
	}
	
	/**
	 * Podla formatu My_Pattern ulozi data do pola 
	 * @return array
	 */
	public function parseToArray(){				
		if(empty($this->_pattern)){
			require_once 'library/My/Csv/Exception.php';
			throw new My_Csv_Exception('Pattern is not set');
		}
		foreach($this->_data as $row){			
			$this->_assocData[] = $this->_pattern->makeArray($row);		
		}
		
		return $this->_assocData;
	}
	
	/**
	 * Zisti typ suboru
	 * @param string $filename
	 */
	private function isRightFileType($file){		
		
		if($file['type'] == self::ALLOWED_FILE_TYPE){
			return true;
		}
		
		return false;			
	}
}